package com.imooc.miaosha.config.resolver;

import com.imooc.miaosha.domian.User;
import com.imooc.miaosha.service.UserService;
import com.imooc.miaosha.system.data.UserThreadLocalContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 模块描述: <br>
 * (对controller层的参数进行校验和封装)
 *
 * @Author: Mr. xyb
 * @Date: 2019/4/17 12:44
 * @since: 1.8.0
 * @version: 1.0.0
 */
@Service
public class UserArgumentResolver implements HandlerMethodArgumentResolver {
    /**
     * 如果方法参数存在User对象则捕获
     *
     * @param methodParameter
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        Class<?> parameterType = methodParameter.getParameterType();
        return parameterType == User.class;
    }

    /**
     * 将对象进行业务处理
     *
     * @param methodParameter
     * @param modelAndViewContainer
     * @param nativeWebRequest
     * @param webDataBinderFactory
     * @return
     * @throws Exception
     */
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory)
            throws Exception {
        Long id = UserThreadLocalContext.get();
        return userService.getUserById(id);

    }

    @Autowired
    private UserService userService;
}
